using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Content.Res;
using Android.Widget;

namespace CPXamarin
{

    //http://tutorialsface.blogspot.com/2014/06/how-to-crop-image-view-as-circle-round.html
    public interface IBitmapHolder
    {
        void SetImageBitmap(Bitmap bmp);
    }

    public static class Images
    {
        public static float ScreenWidth = 320;
        static Dictionary<string, Bitmap> bmpCache = new Dictionary<string, Bitmap>();
        public static async Task SetImageFromUrlAsync(this ImageView imageView, string url)
        {
            var bmp = FromUrl(url);
            if (bmp.IsCompleted)
                imageView.SetImageBitmap(bmp.Result);
            else
                imageView.SetImageBitmap(await bmp);
        }

        public static async Task SetImageFromUrlAsync(IBitmapHolder imageView, string url)
        {
            var bmp = FromUrl(url);
            if (bmp.IsCompleted)
                imageView.SetImageBitmap(bmp.Result);
            else
                imageView.SetImageBitmap(await bmp);
        }

        public static async Task<Bitmap> FromUrl(string url)
        {
            var httpClient = new HttpClient();
            Bitmap bmp = null;

            var imageByte = await httpClient.GetByteArrayAsync(url);

            if(imageByte!=null && imageByte.Length>0)
            {
                bmp = BitmapFactory.DecodeByteArray(imageByte, 0, imageByte.Length);
            }

            return bmp;
        }

        public static Bitmap GetRoundShape(Bitmap scaleBitmapImage)
        {
            int targetWidth = 50;
            int targetHeight = 50;
            using (Bitmap targetBitmap = Bitmap.CreateBitmap(targetWidth, targetHeight, Bitmap.Config.Argb8888))
            {
                Canvas canvas = new Canvas(targetBitmap);
                Path path = new Path();
                path.AddCircle(((float)targetWidth - 1) / 2,
                    ((float)targetHeight - 1) / 2,
                    (Math.Min(((float)targetWidth),
                        ((float)targetHeight)) / 2),
                    Path.Direction.Ccw);

                canvas.ClipPath(path);
                Bitmap sourceBitmap = scaleBitmapImage;
                canvas.DrawBitmap(sourceBitmap,
                    new Rect(0, 0, sourceBitmap.Width,
                        sourceBitmap.Height),
                    new Rect(0, 0, targetWidth, targetHeight), null);
                return targetBitmap;
            }
            
        }
    }
}